package com.bluefoxyu.proxy;

import com.bluefoxyu.common.Invocation;
import com.bluefoxyu.common.URL;
import com.bluefoxyu.loadbalance.Loadbalance;
import com.bluefoxyu.protocol.HttpClient;
import com.bluefoxyu.register.MapRemoteRegister;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory {
    private static final Logger log = LoggerFactory.getLogger(ProxyFactory.class);

    public static <T> T lookup(Class interfaceClass) {
        log.debug("Creating proxy for service: {}", interfaceClass.getName());
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                log.debug("Invoking method: {} on service: {}", method.getName(), interfaceClass.getName());

                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                        method.getParameterTypes(), args);

                HttpClient httpClient = new HttpClient();

                // 服务发现
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());
                if (list == null || list.isEmpty()) {
                    throw new RuntimeException("No service instances registered for: " + interfaceClass.getName());
                }

                URL url = Loadbalance.random(list);
                log.debug("Selected service URL: ://{}:{}/", url.getHostname(), url.getPort());

                // 服务调用
                return httpClient.send(url.getHostname(), url.getPort(), invocation);
            }
        });

        return (T) proxyInstance;
    }
}